package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

/**
 * @author krystal
 * @date 2022/11/27 13:14
 */
public class Demo14 {
    public static void main(String[] args) throws IOException {
        //1.输入路径和要查找的关键词
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入要扫描的路径：");
        File rootDir=new File(scanner.next());
        if (!rootDir.isDirectory()){
            System.out.println("您输入的目录不存在！");
            return;
        }
        System.out.println("请输入要搜索的关键词：");
        String toFind=scanner.next();
        scanDir(rootDir,toFind);
    }

    private static void scanDir(File rootDir, String toFind) throws IOException {
        File[] files=rootDir.listFiles();
        if(files==null){
            //说明rootDir是一个空的目录
            return;
        }
        //如果目录非空，循环遍历每个元素
        for (File f:files){
            if (f.isDirectory()){
                scanDir(f,toFind);
            }else {
                //不是目录，是普通文件，判定文件名是否符合要求，是否要进行删除
                checkDelete(f,toFind);
            }
        }
    }

    private static void checkDelete(File f, String toFind) throws IOException {
        //1.先检查文件名
        if (f.getName().contains(toFind)){
            System.out.println(f.getCanonicalPath()+"文件中包含了"+toFind);
            Scanner scanner=new Scanner(System.in);
            String choice=scanner.next();
            if (choice.equals("Y")||choice.equals("y")){
                f.delete();
            }
        }
        //2.在检查文件内容
        try (InputStream inputStream=new FileInputStream(f)){
            StringBuilder stringBuilder=new StringBuilder();
            Scanner scanner=new Scanner(inputStream);
            while (scanner.hasNextLine()){
                stringBuilder.append(scanner.nextLine()+"\n");
            }
            if (stringBuilder.indexOf(toFind)>-1){
                System.out.println(f.getCanonicalPath()+"文件内容包含"+toFind);
            }
        }
    }
}
